<template>
  <div class="title-dot">

  
    <a-row :gutter="15" class="space-m-b">
      <a-col :md="8" :sm="24">
        <a-card title="转诊流向" class="control-row-first box-shadow box-radius">
          <div slot="extra" ><a-range-picker
            @change="onFlowDateChange"
            :default-value="[moment(refFlowParams.startDate), moment(refFlowParams.endDate,)]"/>
          </div>
          <flow-map :data="refFlow"/>
          <div style="position:absolute; right:30px; bottom:50px;">溆浦县<br/>
            <div class="box-shadow box-radius" style="padding:6px 15px; font-size:12px;">
              转入<span class="font-red" style="font-size:22px;">{{ refFlow.sumcount.in }}</span>人
              <span style="margin:0 5px; color:#ddd;">|</span> 转出<span class="font-primary" style="font-size:22px;">{{ refFlow.sumcount.out }}</span>人
            </div>
          </div>
        </a-card>
      </a-col>
      <a-col :md="9" :sm="24">
        <a-card title="科室转出占比" class="box-shadow box-radius space-m-b">
          <a-empty v-if="!rolloutPieData" style="height:240px;"/>
          <div id="rolloutPie" v-if="rolloutPieData"></div>
        </a-card>
        <a-card title="科室转入占比" class="box-shadow box-radius">
          <a-empty v-if="!rollinPieData" style="height:240px;"/>
          <div id="rollinPie" v-if="rollinPieData"></div>
        </a-card>
      </a-col>
      <a-col :md="7" :sm="24">
        <div class="control-row-first">
          <a-card
            style="width:100%"
            :tab-list="tabList"
            :active-tab-key="tabKey"
            @tabChange="key => onTabChange(key, 'tabKey')"
            class="control-row-first box-shadow box-radius"
          >
            <div v-if="tabKey === 'sortRollin'">
              <a-table
                ref="sortRollinTable"
                :pagination="false"
                :rowKey="(record,index) => record.ranking"
                :columns="sortRollinColumns"
                :data-source="sortRollinTableData">
              </a-table>
            </div>
            <div v-else-if="tabKey === 'sortRollout'">
              <a-table
                ref="sortRolloutTable"
                :pagination="false"
                :rowKey="(record,index) => index"
                :columns="sortRolloutColumns"
                :data-source="sortRolloutTableData">
              </a-table>
            </div>
          <!-- <a slot="tabBarExtraContent" href="#">More</a> -->
          </a-card>
        </div>
      </a-col>
    </a-row>
    <a-row :gutter="15">
      <a-col :sm="12">
        <a-card title="最近转诊申请明细" class="control-row-sec box-shadow box-radius">
          <s-table
            size="default"
            ref="referralUnitDetails"
            :rowKey="(record,index) => index"
            :columns="referralUnitColumns"
            :data="referralUnitLoadData"
            :showPagination="false"
            defaultSort="time"
            :scroll="{ x: false}"
            :pageSize="6"
            :showSizeChanger="false"
          >
          </s-table></a-card>
      </a-col>
      <a-col :sm="12">
        <a-card title="转诊趋势" class="control-row-sec box-shadow box-radius">
          <a-empty v-if="!chartTrend"/>
          <div id="referralTrend" ></div>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script>
import { STable } from '@/components'
import { Chart } from '@antv/g2/lib/index'
import { getDictMap } from '@/utils/dict'
import { refChartTrend, refChartIntoNumber, refRollOutUnit, refFlow, getDiseaseRanking } from '@/api/referral'
import FlowMap from './mapService/map'
import moment from 'moment'
export default {
  name: 'Analysis',
  components: { FlowMap, STable },
  data () {
    return {
      selectedRowKeys: [],
      tabList: [
        {
          key: 'sortRollin',
          tab: '机构转入排行'
        },
        {
          key: 'sortRollout',
          tab: '机构转出排行'
        }
      ],
      tabKey: 'sortRollin',
      sortRollinColumns: [
        {
          title: '排名',
          dataIndex: 'ranking',
          descend: true
        },
        {
          title: '转入机构名称',
          dataIndex: 'hospitalName'
        },
        {
          title: '转入人次',
          dataIndex: 'num'
        }
      ],
      sortRolloutColumns: [
        {
          title: '排名',
          dataIndex: 'ranking',
          ascend: true
        },
        {
          title: '转出机构名称',
          dataIndex: 'hospitalName'
        },
        {
          title: '转出人次',
          dataIndex: 'num'
        }
      ],
      referralUnitLoadData: parameter => {
        return refRollOutUnit(Object.assign({}, parameter)).then((res) => {
          if (res.code === 200) {
            return res.data
          } else {
            this.$message.error(res.message)
          }
        }).catch((err) => {
          this.$message.error('refRollOutUnit:' + err.message)
        })
      },
      referralUnitColumns: [
        {
          title: '申请时间',
          dataIndex: 'time',
          sorter: false,
          width: 190
        },
        {
          title: '转出机构',
          dataIndex: 'outHospitalName',
          ellipsis: true
        },
        {
          title: '患者姓名',
          dataIndex: 'patientName'
        },
        {
          title: '转入机构',
          dataIndex: 'inHospitalName',
          ellipsis: true
        }
      ],
      tableData: [],
      refFlow: {
        sumcount: {
          in: 0,
          out: 0
        }
      },
      refFlowParams: {
        startDate: this.moment(new Date(new Date().getTime() - 30 * 24 * 60 * 60 * 1000)).format('YYYY-MM-DD'),
        endDate: this.moment(new Date()).format('YYYY-MM-DD')
      },
      referralUnitData: null,
      sortRolloutTableData: null,
      sortRollinTableData: null,
      rolloutPieData: null,
      rollinPieData: null,
      chartTrend: null
    }
  },
  methods: {
    moment,
    // onSelectChange (selectedRowKeys, selectedRows) {
    //   console.log('selectedRowKeys', selectedRows)
    //   this.selectedRowKeys = selectedRowKeys
    //   this.selectedRows = selectedRows
    // },
    onFlowDateChange (date, dateString) {
      console.log(dateString)
      this.refFlowParams.startDate = dateString[0]
      this.refFlowParams.endDate = dateString[1]
      this.loadData(refFlow, (data) => {
        this.refFlow = data
      }, this.refFlowParams
      )
    },
    onTabChange (key, type) {
      console.log(key, type)
      this[type] = key
    },
    getIntoNumberSort (key) {
      const index = String(key)
      this.loadData(refChartIntoNumber, (data) => {
        console.log('refChartNumber' + key, data)
        if (index === '1') {
          this.sortRollinTableData = data
        } else {
          this.sortRolloutTableData = data
        }
      }, {
        pageSize: 10,
        pageNum: 1,
        unitRanking: index
      })
    },
    loadData (api, call, params) {
      api(params).then((res) => {
        if (res.code === 200) {
          call(res.data)
        } else {
          this.$message.error(res.message)
        }
      }).catch((err) => {
        this.$message.error(api + ':' + err.message)
      })
    },
    referralPieInit (id, data, dimension, params) {
      const { height } = params
      const chart = new Chart({
        container: id,
        autoFit: true,
        height: height || 500
      })
      chart.data(data)
      chart.scale('percent', {
        formatter: (val) => {
          val = parseFloat(val * 100).toFixed(0) + '%'
          return val
        }
      })
      chart.coordinate('theta', {
        radius: 0.75,
        innerRadius: 0.6
      })
      chart.tooltip({
        showTitle: false,
        showMarkers: false,
        itemTpl: '<li class="g2-tooltip-list-item"><span style="background-color:{color};" class="g2-tooltip-marker"></span>{name}: {value}</li>'
      })
      // 辅助文本
      // chart
      //   .annotation()
      //   .text({
      //     position: ['50%', '50%'],
      //     content: '',
      //     style: {
      //       fontSize: 14,
      //       fill: '#8c8c8c',
      //       textAlign: 'center'
      //     },
      //     offsetY: -20
      //   })
      chart
        .interval()
        .adjust('stack')
        .position('percent')
        .color('item', ['#5da0fd', '#83cfff', '#a6f3ff', '#98df73', '#f4be38', '#ac89f1'])
        .label('percent', (percent) => {
          return {
            content: (data) => {
              let pielabel = ''
              if (percent > 0.06) {
                pielabel = `${data[dimension]}: ${parseFloat(percent * 100).toFixed(0)}%`
              }
              return pielabel
            }
          }
        })
        .tooltip(`${dimension}*percent`, (item, percent) => {
          percent = parseFloat(percent * 100).toFixed(0) + '%'
          return {
            name: item,
            value: percent
          }
        })
      chart.interaction('element-active')
      chart.legend({
        position: 'right',
        offsetX: 0,
        itemGap: 20
      })
      chart.render()
    },
    referralTrendInit (id, data, dimension, params) {
      const { height } = params
      const chart = new Chart({
        container: id,
        autoFit: true,
        height: height || 300
      })
      var arr = []
      data.forEach((item) => {
        arr.push(item.y)
      })
      var max = Math.max(...arr) + Math.max(...arr) * 0.5
      chart.data(data)
      chart.scale({
        x: {
          // nice: true
        },
        y: {
          // nice: true,
          min: 0,
          max: max
        }
      })

      chart.tooltip({
        showCrosshairs: true,
        shared: true
      })

      chart.axis('y', {
        label: {
          formatter: (val) => {
            return val
          }
        }
      })

      chart
        .line()
        .position('x*y')
        .color(dimension)
      // .shape('smooth')

      chart
        .point()
        .position('x*y')
        .color(dimension)
        .shape('circle')

      chart.render()
    }
  },
  mounted () {
    // 转诊申请明细
    this.loadData(refRollOutUnit, (data) => {
      console.log('unitdatainit', data)
      this.referralUnitData = data.rows
    })
    // 机构转入转出排行
    this.getIntoNumberSort(0)
    this.getIntoNumberSort(1)
    // 转诊趋势
    // this.referralTrendInit('referralTrend', this.chartTrend, 'hospitalTurn', { height: 400 })
    this.loadData(refChartTrend, (cdata) => {
      console.log('refChartTrend', cdata)
      function createLineChart (data, dictlist, _this) {
        const res = [...data.dataList]
        if (res.length > 0) {
          const newData = []
          res.forEach((item, index) => {
            newData.push({
              x: item.time,
              y: Number(item.num),
              hospitalTurn: dictlist.get(item.flow)
            })
          })
          // const tempdata = [
          //   { x: '2020-07', hospitalTurn: '上转', y: 7 },
          //   { x: '2020-07', hospitalTurn: '下转', y: 3.9 },
          //   { x: '2020-08', hospitalTurn: '上转', y: 6.9 },
          //   { x: '2020-08', hospitalTurn: '下转', y: 4.2 },
          //   { x: '2020-09', hospitalTurn: '上转', y: 9.5 },
          //   { x: '2020-09', hospitalTurn: '下转', y: 5.7 },
          //   { x: '2020-10', hospitalTurn: '上转', y: 14.5 },
          //   { x: '2020-10', hospitalTurn: '下转', y: 8.5 },
          //   { x: '2020-11', hospitalTurn: '上转', y: 18.4 },
          //   { x: '2020-11', hospitalTurn: '下转', y: 11.9 },
          //   { x: '2020-12', hospitalTurn: '上转', y: 21.5 },
          //   { x: '2020-12', hospitalTurn: '下转', y: 15.2 }
          // ]
          _this.chartTrend = newData
          console.log('refChartTrendnewData', _this.chartTrend)
          _this.referralTrendInit('referralTrend', _this.chartTrend, 'hospitalTurn', { height: 400 })
        }
      }
      getDictMap('refhospitalTurn').then(dictlist => {
        createLineChart(cdata, dictlist, this)
      })
    })
    // 科室转出转入占比分析
    this.loadData(getDiseaseRanking, (data) => {
      console.log('rolloutPieData', data)
      this.rolloutPieData = data.out || ''
      this.rollinPieData = data.in || ''
      this.$nextTick(() => {
        this.rolloutPieData && this.referralPieInit('rolloutPie', this.rolloutPieData, 'item', { height: 240 })
        this.rollinPieData && this.referralPieInit('rollinPie', this.rollinPieData, 'item', { height: 240 })
      })
    })
    // 转诊流向图
    this.loadData(refFlow, (data) => {
      this.refFlow.sumcount.in = data.sumcount.in
      this.refFlow.sumcount.out = data.sumcount.out
      this.$set(this.refFlow, 'RefFlowOut', data.RefFlowOut)
      this.$set(this.refFlow, 'direction', data.direction)
    }, this.refFlowParams)
  }
}

</script>

<style>
.control-row-first {
  height: 697px !important;
}
.control-row-sec {
  height: 500px !important;
}
</style>
